<template>
  <div class="k-box">
    <div class="btn">
      <ElButton @click="selectEcharts('up')">上</ElButton>
      <ElButton @click="selectEcharts('down')">下</ElButton>
    </div>
    <div class="box" v-loading="loading">
      <ECharts :option="macdOption" ref="echartsRef" :handle-data-zoom="handleDataZoom"> </ECharts>
    </div>
  </div>
</template>

<script setup lang="ts" name="home">
import { useMACDData } from "./hooks/use-macd";
import { useCommon } from "./hooks/use-common";

const { option: macdOption, loading, setMaxY } = useMACDData();
const { getMaxAndMinValue } = useCommon();

let echartsRef = ref<any>(null);
let useIndex = ref(-1);
let selectOp = ref<any>([]);

onBeforeMount(() => {
  init();
});

const selectEcharts = async (flag: "up" | "down") => {
  if (flag == "up") {
    useIndex.value--;
  } else {
    useIndex.value++;
  }
  const params = {
    dm: selectOp.value[useIndex.value].code
  };
  const data: any = await homeFindHistoryK(params);
  const { date, macd, dea, dif, k, cci, ma5, ma30, ma10, ma20 } = data || {};
  macdOption.value.xAxis[0].data = date;
  macdOption.value.series[0].data = macd;
  macdOption.value.series[1].data = dea;
  macdOption.value.series[2].data = dif;
  macdOption.value.series[3].data = k;
  macdOption.value.series[4].data = cci;

  macdOption.value.series[5].data = ma5;
  macdOption.value.series[6].data = ma10;
  macdOption.value.series[7].data = ma20;
  macdOption.value.series[8].data = ma30;

  loading.value = false;
  // nextTick(() => {
  //   handleDataZoom({
  //     start: 98,
  //     end: 100
  //   });
  // });
};

//  初始化
const init = async () => {
  loading.value = true;
  selectOp.value = await tapePurchaseHistoryFindTapePurchase();
  selectEcharts("down");
  loading.value = false;
};
const handleDataZoom = (params: any) => {
  // macd
  const data0 = echartsRef.value?.getInstance().getOption().series[0].data;
  // k 线
  const data3 = echartsRef.value?.getInstance().getOption().series[3].data;
  // cci
  const data4 = echartsRef.value?.getInstance().getOption().series[4].data;

  const { max } = getMaxAndMinValue(params, data3);
  const { min: min0 } = getMaxAndMinValue(params, data0);
  const { min: min4, max: max4 } = getMaxAndMinValue(params, data4);

  setMaxY(max, min0, { max4, min4 });

  macdOption.value.dataZoom.start = params.start;
  macdOption.value.dataZoom.end = params.end;
};
</script>

<style scoped lang="scss" src="./index.scss"></style>
